/**
 * Turbo Fixes - Simplified Version
 * 专注于核心功能的SPA导航脚本
 */
(function() {
    'use strict';

    // 全局TurboFixes对象
    window.TurboFixes = {
        initialized: false,
        _treasureKeydownBound: false,
        _live2dInitialized: false,

        init: function() {
            if (this.initialized) return;
            console.log('TurboFixes: Simplified Initializing...');
            this.setupTurboEvents();
            this.initializePage();
            this.initializeLive2DWidget();
            this.initialized = true;
            console.log('TurboFixes: Simplified Initialization Complete.');
        },

        setupTurboEvents: function() {
            document.addEventListener('turbo:load', () => { this.initializePage(); this.initializeLive2DWidget(); });
            document.addEventListener('turbo:render', () => {
                this.cleanupHeadPageStyles();
                this.initializeBootstrapComponents();
            });
            document.addEventListener('turbo:before-cache', () => this.cleanupBeforeCache());
        },

        initializePage: function() {
            this.cleanupHeadPageStyles();
            this.initializeBootstrapComponents();
            this.fixPageSpecificIssues();
            this.initializeTreasurePage();
        },

        initializeBootstrapComponents: function() {
            if (typeof bootstrap === 'undefined') return;

            // 清理旧的实例
            document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(el => {
                const inst = bootstrap.Tooltip.getInstance(el);
                if (inst) inst.dispose();
            });
            document.querySelectorAll('[data-bs-toggle="popover"]').forEach(el => {
                const inst = bootstrap.Popover.getInstance(el);
                if (inst) inst.dispose();
            });

            // 初始化新的实例
            const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            tooltipTriggerList.map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));

            const popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
            popoverTriggerList.map(popoverEl => new bootstrap.Popover(popoverEl));
        },

        fixPageSpecificIssues: function() {
            // 修复Markdown编辑器问题
            if (document.getElementById('markdown-editor') && typeof window.initializePage === 'function') {
                window.initializePage();
            }
            // 修复管理页面问题
            if (document.getElementById('aboutContent') && typeof window.initializeAdminPage === 'function') {
                window.initializeAdminPage();
            }
        },

        // ========= 百宝箱页面：在Turbo下的无刷新初始化 =========
        initializeTreasurePage: function() {
            const grid = document.getElementById('treasureGrid');
            if (!grid) return; // 非百宝箱页面

            const searchInput = document.getElementById('searchInput');
            const emptyState = document.getElementById('emptyState');
            const noResults = document.getElementById('noResults');
            const filterTabs = document.querySelectorAll('.filter-tab');
            let currentFilter = 'all';
            const items = Array.from(document.querySelectorAll('.treasure-item'));

            const filterItems = (keyword, filter) => {
                let visible = 0;
                items.forEach(item => {
                    const name = (item.dataset.name || '').toLowerCase();
                    const type = item.dataset.type;
                    const matchesKeyword = !keyword || name.includes(keyword);
                    const matchesFilter = filter === 'all' || type === filter;
                    if (matchesKeyword && matchesFilter) { item.style.display = 'flex'; visible++; }
                    else { item.style.display = 'none'; }
                });
                if (visible === 0) {
                    grid.style.display = 'none';
                    if (emptyState) emptyState.style.display = keyword ? 'none' : 'block';
                    if (noResults) noResults.style.display = keyword ? 'block' : 'none';
                } else {
                    grid.style.display = 'grid';
                    if (emptyState) emptyState.style.display = 'none';
                    if (noResults) noResults.style.display = 'none';
                }
            };

            const previewFileById = (id, filePath, fileName, mime) => {
                if (typeof bootstrap === 'undefined') return;
                const titleEl = document.getElementById('filePreviewTitle');
                const frameEl = document.getElementById('filePreviewFrame');
                const unsupportedEl = document.getElementById('filePreviewUnsupported');
                const dlBtn = document.getElementById('fileDownloadBtn');
                if (titleEl) titleEl.textContent = fileName || '文件预览';
                if (dlBtn) {
                    dlBtn.href = id ? ('/treasure/download/' + id) : (filePath || '#');
                    dlBtn.download = fileName || '';
                }
                const ext = (fileName || '').split('.').pop().toLowerCase();
                const isImage = (mime && mime.startsWith('image/')) || ['jpg','jpeg','png','gif','bmp','webp','svg'].includes(ext);
                const isPdf = (mime && mime.toLowerCase().includes('pdf')) || ext === 'pdf' || (filePath && filePath.toLowerCase().endsWith('.pdf'));
                if (isImage || isPdf) {
                    if (unsupportedEl) unsupportedEl.style.display = 'none';
                    if (frameEl) {
                        frameEl.style.display = 'block';
                        frameEl.src = id ? ('/treasure/preview/' + id) : (filePath || 'about:blank');
                    }
                } else {
                    if (frameEl) { frameEl.src = 'about:blank'; frameEl.style.display = 'none'; }
                    if (unsupportedEl) unsupportedEl.style.display = 'block';
                }
                new bootstrap.Modal(document.getElementById('filePreviewModal')).show();
            };

            // 绑定点击（避免重复绑定）
            items.forEach(item => {
                if (item.dataset.boundClick === '1') return;
                item.addEventListener('click', () => {
                    const type = item.dataset.type;
                    if (type === 'website') {
                        const url = item.dataset.url;
                        if (url) window.open(url, '_blank');
                    } else {
                        const file = item.dataset.file;
                        const name = item.dataset.filename;
                        const mime = item.dataset.mime;
                        const id = item.dataset.id;
                        previewFileById(id, file, name, mime);
                    }
                });
                item.dataset.boundClick = '1';
            });

            // 搜索框与提示（避免重复绑定）
            if (searchInput && searchInput.dataset.boundInput !== '1') {
                searchInput.addEventListener('input', function() {
                    const keyword = this.value.toLowerCase().trim();
                    filterItems(keyword, currentFilter);
                });
                searchInput.addEventListener('focus', function(){ this.placeholder = '输入关键词搜索... (ESC 清空)'; });
                searchInput.addEventListener('blur', function(){ this.placeholder = '搜索百宝箱项目...'; });
                searchInput.dataset.boundInput = '1';
            }

            // 筛选标签（避免重复绑定）
            filterTabs.forEach(tab => {
                if (tab.dataset.boundClick === '1') return;
                tab.addEventListener('click', function(e) {
                    e.preventDefault();
                    filterTabs.forEach(t => t.classList.remove('active'));
                    this.classList.add('active');
                    currentFilter = this.dataset.filter || 'all';
                    const keyword = searchInput ? searchInput.value.toLowerCase().trim() : '';
                    filterItems(keyword, currentFilter);
                });
                tab.dataset.boundClick = '1';
            });

            // 键盘快捷键（仅绑定一次）
            if (!this._treasureKeydownBound) {
                document.addEventListener('keydown', function(e) {
                    if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
                        e.preventDefault();
                        if (searchInput) searchInput.focus();
                    }
                    if (e.key === 'Escape' && document.activeElement === searchInput) {
                        searchInput.value = '';
                        filterItems('', currentFilter);
                    }
                });
                this._treasureKeydownBound = true;
            }

            // 模态框清理（避免重复绑定）
            const previewModalEl = document.getElementById('filePreviewModal');
            if (previewModalEl && previewModalEl.dataset.boundHide !== '1') {
                previewModalEl.addEventListener('hidden.bs.modal', function(){
                    const frame = document.getElementById('filePreviewFrame');
                    if (frame) frame.src = '';
                });
                previewModalEl.dataset.boundHide = '1';
            }

            // 初始状态检查
            if (items.length === 0) {
                grid.style.display = 'none';
                if (emptyState) emptyState.style.display = 'block';
            } else {
                const keyword = searchInput ? searchInput.value.toLowerCase().trim() : '';
                filterItems(keyword, currentFilter);
            }
        },

        // ========= Turbo 渲染时清理旧页面样式，避免样式串页 =========
        cleanupHeadPageStyles: function() {
            const styles = Array.from(document.head.querySelectorAll('style[data-page-style]'));
            if (styles.length <= 1) return;
            const keep = styles[styles.length - 1];
            styles.slice(0, -1).forEach(s => {
                if (s !== keep && s.parentNode) s.parentNode.removeChild(s);
            });
        },

        cleanupBeforeCache: function() {
            // 清理EasyMDE实例
            if (window.easyMDEInstance) {
                try {
                    window.easyMDEInstance.toTextArea();
                    window.easyMDEInstance = null;
                } catch (e) {
                    console.warn('TurboFixes: Failed to cleanup EasyMDE instance.', e);
                }
            }
        },
        initializeLive2DWidget: function() {
            // 仅在首页和分类页面显示人偶，其它页面移除
            const path = (window.location && window.location.pathname) || '/';
            const shouldShow = (path === '/' || path.startsWith('/category/'));
            const existing = document.getElementById('live2d-widget');

            if (!shouldShow) {
                if (existing && existing.parentNode) {
                    existing.parentNode.removeChild(existing);
                }
                // 允许在后续进入允许页面时重新初始化
                this._live2dInitialized = false;
                return;
            }

            // 已在允许页面且元素存在则不重复初始化；如果被移除则允许重新初始化
            if (this._live2dInitialized && existing) return;

            const initWithModelUrl = (modelUrl) => {
                try {
                    window.L2Dwidget.init({
                        model: { jsonPath: modelUrl, scale: 1 },
                        display: { position: 'right', width: 280, height: 350, hOffset: 0, vOffset: 0 },
                        mobile: { show: true, scale: 0.8 },
                        react: { opacityDefault: 1, opacityOnHover: 1 },
                        log: false
                    });
                    setTimeout(() => {
                        const el = document.getElementById('live2d-widget');
                        if (el) {
                            el.style.right = '0px';
                            el.style.bottom = '0px';
                            el.style.zIndex = '1100';
                            el.style.pointerEvents = 'auto';
                            el.setAttribute('data-turbo-permanent', '');
                        }
                    }, 0);
                    this._live2dInitialized = true;
                } catch (e) {
                    console.error('TurboFixes: Live2D init failed', e);
                }
            };

            const modelUrls = [
                'https://cdn.jsdelivr.net/npm/live2d-widget-model-shizuku@1.0.5/assets/shizuku.model.json',
                'https://fastly.jsdelivr.net/npm/live2d-widget-model-shizuku@1.0.5/assets/shizuku.model.json',
                'https://npm.elemecdn.com/live2d-widget-model-shizuku@1.0.5/assets/shizuku.model.json'
            ];

            const probeAndInit = () => {
                let chosen = null;
                const probe = (i) => {
                    if (i >= modelUrls.length) { initWithModelUrl(modelUrls[0]); return; }
                    fetch(modelUrls[i], { method: 'HEAD', mode: 'cors' })
                        .then(() => { chosen = modelUrls[i]; initWithModelUrl(chosen); })
                        .catch(() => probe(i+1));
                };
                probe(0);
            };

            if (typeof window.L2Dwidget === 'undefined') {
                console.warn('TurboFixes: Live2D library not loaded yet. Attempting fallback load...');
                this.ensureLive2DLibraryLoaded(probeAndInit);
            } else {
                probeAndInit();
            }
        },
        ensureLive2DLibraryLoaded: function(onReady) {
            if (typeof window.L2Dwidget !== 'undefined') { onReady && onReady(); return; }
            const cdns = [
                'https://cdn.jsdelivr.net/npm/live2d-widget@3.1.4/lib/L2Dwidget.min.js',
                'https://fastly.jsdelivr.net/npm/live2d-widget@3.1.4/lib/L2Dwidget.min.js',
                'https://npm.elemecdn.com/live2d-widget@3.1.4/lib/L2Dwidget.min.js'
            ];
            const tryLoad = (i) => {
                if (i >= cdns.length) { console.warn('TurboFixes: Failed to load Live2D library from all CDNs.'); return; }
                const s = document.createElement('script');
                s.src = cdns[i];
                s.defer = true;
                s.onload = () => { onReady && onReady(); };
                s.onerror = () => { console.warn('TurboFixes: CDN failed', cdns[i]); tryLoad(i+1); };
                document.head.appendChild(s);
            };
            tryLoad(0);
        },
    };

    // 自动初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => window.TurboFixes.init());
    } else {
        window.TurboFixes.init();
    }
})();